package com.lili.other;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2024/8/24
 * @Description: 355.设计推特
 * @version: 1.0
 */
//推特类
public class Twitter {
    public Twitter() {

    }

    //发布文章
    public void postTweet(int userId, int tweetId) {
        //获取用户对象
        User user = userMap.computeIfAbsent(userId, User::new);
        Tweet tweet = new Tweet(tweetId, time++, user.head.next);
        user.head.next = tweet;
    }

    //返回文章10篇最新
    public List<Integer> getNewsFeed(int userId) {
        User user = userMap.get(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        PriorityQueue<Tweet> queue = new PriorityQueue<>(Comparator.comparingInt(Tweet::getTime).reversed());
        if (user.head.next != null) {
            queue.offer(user.head.next);
        }
        for (Integer id : user.follow) {
            User followUser = userMap.get(id);
            if (followUser.head.next != null) {
                queue.offer(followUser.head.next);
            }
        }
        List<Integer> res = new ArrayList<>();
        int count = 0;
        while (!queue.isEmpty() && count < 10) {
            Tweet poll = queue.poll();
            res.add(poll.id);
            if (poll.next != null) {
                queue.offer(poll.next);
            }
            count++;
        }
        return res;
    }

    //新增关注
    public void follow(int userId, int followeeId) {
        User user = userMap.computeIfAbsent(userId, User::new);
        User follow = userMap.computeIfAbsent(followeeId, User::new);
        user.follow.add(follow.id);
    }

    //取消关注
    public void unfollow(int userId, int followeeId) {
        User user = userMap.get(userId);
        if (user != null) {
            user.follow.remove(followeeId);
        }
    }

    //维护用户的属性,k用户id,user用户
    private final Map<Integer, User> userMap = new HashMap<>();

    //文章时间
    private static int time;

    //文章类
    class Tweet {
        int id;
        int time;
        Tweet next;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getTime() {
            return time;
        }

        public void setTime(int time) {
            this.time = time;
        }

        public Tweet getNext() {
            return next;
        }

        public void setNext(Tweet next) {
            this.next = next;
        }

        public Tweet(int id, int time, Tweet next) {
            this.id = id;
            this.time = time;
            this.next = next;
        }
    }

    //用户类
    class User {
        //id
        int id;
        //关注的用户
        Set<Integer> follow = new HashSet<>();
        //用户发布的文章
        Tweet head = new Tweet(-1, -1, null);

        public User(int id) {
            this.id = id;
        }
    }
}
